\chapter{Design patterns support}
\label{chap:dpsupport}
Even though design patterns cannot be completely implemented as reusable libraries, 
there is room for some automation which can be handled by the software to overcome 
some of the disadvantages of design patterns. 
Software tools may enhance the implementation of 
design patterns on the source code level, for example, by code generation or refactoring. 
On the higher level of abstraction, during the modeling of class diagrams in UML, 
tools may direct a designer to introduce suitable patterns in the design. 
Verification of patterns implementation on either the source code level or 
the higher level object design (like UML class diagrams) could be useful 
for discovering software bugs and could prevent from communication errors, 
when, for instance, one of the team members is used to use a little bit 
different variation of some design pattern than the others in the team. 

\section{Patterns formalization and verification}
\label{sec:patterns-formalization}	
	Design patterns used to be described only in an informal manner in natural 
	language using graphical diagrams, usually complemented with code examples. 
	This representation, useful for human beings, is not suitable for a rigorous 
	reasoning (e.g., for formal verification) and obstructs any automation tools support. 
	The need for a formal specification of design patterns is obvious. 
	In this section we discuss the patterns formalization techniques. 
	It is important to note that formalization of 
	patterns is not intended to replace the informally written pattern catalogs, 
	which are ideal for learning purposes.
	
	A pattern in object-oriented design consists of several elements. In the 
	introduction we mention a description, a solution and consequences. 
	These parts could also be broken down into smaller pieces. The solution part 
	can decomposed to a structural aspect and a behavioral aspect. 
	In this section we focus on the structural aspect of the solution part.
	
	The solution part of a design pattern always contains some degree of flexibility. 
	In the introduction we provide an example of the \pattern{Composite} pattern and we 
	explain that the composite operation \inlinecode{getWidth} may be implemented as 
	the mean of all widths or the width of the largest children component. This kind of 
	flexibility is what makes the \pattern{Composite} pattern a pattern and not 
	an adept for an aspect or a generated class using meta programming
	\footnote{Aspects and meta programming with connection to patterns are discussed 
	in section \ref{sec:coding-support}}. Some authors assume that the \pattern{Composite} 
	pattern should always have the methods for adding and removing components 
	\cite{taibi2007design}. The "children related operations" 
	are indeed mentioned in \cite{gamma1995design}, but does it mean 
	that a \pattern{Composite} 
	class must always be mutable (allow to change it's children collection)? 
	Does it mean that immutable quasi \pattern{Composite} class that does not 
	allow adding or removing children after it's creation does not implement the \pattern{Composite} 
	pattern, even though it clearly solves the problem solved by the 
	\pattern{Composite} pattern and it does it in very similar way? 
	These questions might be another evidence for the need for a precise 
	pattern formalization. But the approach should balance the degree of formalization 
	and the degree of flexibility. We think that during the process of actual 
	formalization of concrete patterns the informal description 
	should not be translated literally, because otherwise, the formal verification 
	would be unnecessarily strict and thus would go against 
	the flexibility developers expect from design patterns.
	
	Another thing to note is that some patterns are different in the problem part, 
	but their solution parts are almost the same. The \pattern{Bridge} and the 
	\pattern{Adapter} patterns differ only in the intent: the \pattern{Bridge} 
	is used during the design phase, but the \pattern{Adapter} is used 
	to wire up already existing classes.		

	\paragraph*{Structural formalization}	
	\subparagraph*{}
	Most of the design patterns solutions involve more cooperating classes or objects.
	The term participant or the term role is used frequently.
	In the \pattern{Composite} pattern solution we have a \patternrole{Composite} class, 
	\patternrole{Leaf} objects and a \patternrole{Component}, the base interface 
	for \patternrole{Composite} and \patternrole{Leafs}. This implies that 
	if we have a set of real classes and we choose one to play the role of 
	the \patternrole{Component} and one to play the role of the \patternrole{Composite}, 
	the \patternrole{Component} class must inherit from \patternrole{Composite} 
	class (or implement \patternrole{Composite} interface in the languages such as C\#), 
	otherwise it is not a correct implementation of the \pattern{Composite} pattern. 
	This is a simple example of a structural aspect of the \pattern{Composite} pattern 
	solution, whose formalization could be rather straightforward. The same holds 
	for the fact that in a valid implementation of this pattern the \patternrole{Composite} 
	class should aggregate a collection or a list of \patternrole{Components}.
	
	The \pattern{Composite} pattern solution also guides us to implement the operations 
	on \patternrole{Composite} class by delegation to the \patternrole{Components}. 
	This is more complicated to formalize since a delegation to the 
	\patternrole{Components} can have several different forms. The special 
	case might be a situation when the composite operation returns a cached value, 
	which is refreshed after each addition or removal of a child. 
	Besides this very special case we could say that the composite operations should 
	iterate over the \patternrole{Components} collection. Could we also say that 
	a composite operation should always call the corresponding operation on 
	each of the \patternrole{Components}? 
	It all depends on the degree of flexibility we want to have in our 
	formalization. Most of the approaches presented in \cite{taibi2007design} 
	are relatively strict. On the other hand in Patterns4Net we went for more 
	flexible formal specifications of patterns solutions and we verify only 
	the core aspects, which should be fulfilled almost always. Thus the 
	users of Patterns4Net can still take the advantage of some flexibility 
	in design patterns implementations.
		
	In the previous two paragraphs we rather informally describe how the 
	formalization of patterns structural aspects could work. To make the approach 
	of formalization complete we need some instrument to precisely capture the rules which 
	should be fulfilled by the structure of a correctly implemented pattern. 
	The existing formalization techniques are usually based on mathematical formalisms. 
	For example, the Balanced pattern specification language (BPSL, \cite{taibi2007designbspl}) 
	leverages the first-order logic, because the relations between pattern roles can 
	be easily expressed as predicates.
	In BSPL a pattern is specified using the first-order language called $S_{BSPL}$,
	where variable and constant symbols represent classes, typed variables and methods, 
	sets of these are designated C, V and M.
	$S_{BSPL}$ provides predicates (BSPL authors use the term relation) such as  
	$Invocation(m_1,m_2)$ where $m_1, m_2 \in M$, which evaluates to true iff\footnote{if and only if} 
	method $m_1$ invokes method $m_2$. The structural specification of the \pattern{Observer} 
	pattern in $S_{BSPL}$ is given in the figure~\ref{fig:observersbsp}. 
	The English names of the predicates are self-describing.	
	\begin{figure}[h]				
		\small{		
		\begin{align*}
		& \exists \textit{subject}, \textit{concrete\_subject}, \textit{observer}, \textit{concrete\_observer} \in C; \\
		& \exists \textit{subject\_state}, \textit{observer\_state} \in V; \\
		& \exists \textit{attach}, \textit{detach}, \textit{notify}, \textit{get\_state}, \textit{set\_state}, \textit{update} \in M: \\		
		& \textit{Defined\_in}(\textit{subject\_state}, \textit{concrete\_subject}) \wedge {}\\
		& \textit{Defined\_in}(\textit{observer\_state}, \textit{concrete\_observer}) \wedge {}\\
		& \textit{Defined\_in}(\textit{attach}, \textit{subject}) \wedge 
		  \textit{Defined\_in}(\textit{detach}, \textit{subject}) \wedge {}\\
		& \textit{Defined\_in}(\textit{notify}, \textit{subject}) \wedge 
		  \textit{Defined\_in}(\textit{set\_state}, \textit{concrete\_subject}) \wedge {}\\
		& \textit{Defined\_in}(\textit{get\_state}, \textit{concrete\_subject}) \wedge
		  \textit{Defined\_in}(\textit{update}, \textit{observer}) \wedge {}\\
		& \textit{Reference\_to\_one}(\textit{concrete\_observer}, \textit{concrete\_subject}) \wedge {}\\
		& \textit{Reference\_to\_many}(\textit{subject}, \textit{observer}) \wedge {}\\
		& \textit{Inheritance}(\textit{concrete\_subject}, \textit{subject}) \wedge 
		  \textit{Inheritance}(\textit{concrete\_observer}, \textit{observer}) \wedge {}\\
		& \textit{Invocation}(\textit{set\_state}, \textit{notify}) \wedge 
		  \textit{Invocation}(\textit{notify}, \textit{update}) \wedge {}\\
		& \textit{Invocation}(\textit{update}, \textit{get\_state}) \wedge 
		  \textit{Argument}(\textit{observer}, \textit{attach}) \wedge {}\\
		& \textit{Argument}(\textit{observer}, \textit{detach}) \wedge 
		  \textit{Argument}(\textit{subject}, \textit{update})
		\end{align*}
		}
		\caption{The structural specification of the \pattern{Observer} pattern in $S_{BSPL}$}
		\label{fig:observersbsp}
	\end{figure}
		
	To employ such formalization in a practical use for a verification or a recognition, 
	we need to evaluate the predicates according to a source code or another representation 
	of an object oriented program. An interesting proposal is discussed by 
	the authors of SPINE \cite{taibi2007designspine}. They suggest to use Prolog 
	language. We can represent the constraints for pattern structure as Prolog rules and 
	those rules that depend on source code analysis (e.g., $Invocation$) can be added to 
	the Prolog program database using \inlinecode{assert} or removed using \inlinecode{retract}. 
	The SPINE language they present is based on Prolog and it comes with HEDGEHOG 
	which is a proof engine that parses Java programs, adds the corresponding rules 
	to the database and then is able to answer questions such as 
	standard Prolog program; for example, whether specific 
	class implements the \pattern{Singleton} pattern or whether 
	a class that implements the \pattern{Composite} pattern exists in the database. 
	The figure~\ref{fig:spine} shows structural specification of 
	a variant of the \pattern{Singleton} pattern in SPINE and 
	a Java class that implements the \pattern{Singleton} pattern according 
	to this specification.	
	\begin{figure}[h]
		\begin{lstlisting}[language=Prolog]
realises('PublicSingleton',[C]) :-
	exists(constructorsOf(C),true),
	forAll(constructorsOf(C), Cn.isPrivate(Cn)),
	exists(fieldsOf(C),F.and([
		isStatic(F),
		isPublic(F),
		isFinal(F),
		typeOf(F,C),
		nonNull(F)
	])).
		\end{lstlisting}			
		
		\begin{lstlisting}[language=Java]
public class PublicSingleton {
	public static final PublicSingleton 
		instance = new PublicSingleton();
	private PublicSingleton() {}
}
		\end{lstlisting}
		\caption{The \pattern{Singleton} pattern in SPINE and Java.}
		\label{fig:spine}
	\end{figure}
		
	A promising approach might be to express patterns as stereotypes in UML 
	and use the Object Constraint Language (OCL, \cite{warmer1998object}) to 
	express the stereotype constraints. UML, as a part of the Model Driven Architecture 
	(MDA, \cite{kleppe2003mda}), is widely used technology and so the OCL, 
	also part of the MDA, might become popular and widely used as 
	well in the future. 
		
	Another approach leverages the semantic Web technologies 
	\cite{taibi2007designsemweb}. Design patterns can be defined as RDF documents 
	instantiating a vocabulary based on the Web ontology language (OWL). 
	This approach also promotes the usage of design patterns as a knowledge shared 
	among software developers. Lastly the LePUS3 \cite{nicholson2009automated}, 
	which is one of the most accepted and well known approaches 
	for design patterns formalization, provides 
	graphical notation for expressing the structural aspects of design patterns. 
	The figure~\ref{fig:lepus} shows specification of the \pattern{Composite} 
	pattern in the LePUS3. 
	It can be seen that graphical notation provides more lucid  
	(in comparison to textual forms) form of specifying the structural aspects. 	
	\begin{figure}
		\mbox{\includegraphics[width=85mm]{images/composite-lepus.png}}
		\caption{Specification of the \pattern{Composite} pattern in LePUS3.}
		\label{fig:lepus}
	\end{figure}
	
\section{The role of programming language}	
\label{sec:coding-support}	
	The choice of a programming language determines what can and what cannot be 
	implemented easily. In \cite{gamma1995design} the authors assume 
	Smalltalk/C++-level language 
	features. If they assumed procedural languages, they might introduce patterns 
	such as "Inheritance" or "Encapsulation". But there are also important differences 
	between object-oriented languages. For example Groovy 
	\cite{groovy:Online} supports the multiple dispatch, 
	which lessens the need for the \pattern{Visitor} 
	pattern. 
	
	\subsection{New features}
	Since the first publication of \cite{gamma1995design}, the mainstream programming 
	languages went through an evolution. For example, lambda expressions are supported 
	in C\# since version 3.0, new versions of PHP, Java and new C++ 
	specification all include lambda functions. This is four of the top five most 
	popular languages \cite{tiobeIndex:Online}, therefore we can say that 
	nowadays lambda functions can be considered as an essential feature. Let us 
	investigate what lambda functions may bring for design patterns.		
	In most design patterns solutions a polymorphism is used to "inject" some logic 
	that will be implemented later on and can be swapped for another. 
	This brings flexibility to the design. 	
	
	The \pattern{Template method} pattern might be a good example. 
	It defines a skeleton of an algorithm and one or more steps of the algorithm 
	might be altered in the subclasses by overriding virtual methods. 
	When we have lambda functions we may use them to achieve the similar 
	flexibility. The new version of the \pattern{Template method} pattern with lambda 
	functions does not invoke virtual methods, but the lambda functions that are 
	passed to it as parameters, or that are given to the object as 
	constructor parameters. This alternative imlementation does not require 
	to create a new class each time we want to implement a new set of steps 
	that alternate the algorithm. On the other hand we have to provide the lambda 
	functions and if they are long enough we may still end up with refactoring 
	them to methods and these methods to a new class. 
	A good compromise might be to implement the 
	\pattern{Template method} as usual, but provide a subclass that invokes 
	lambda functions, which it gets as constructor parameters. The method 
	\inlinecode{ForEach(Action)} from the \inlinecode{List} class from 
	the .NET Base Class Library might be considered as a simple example 
	of such \pattern{Template method} with lambda function.	
	
	Another well known example of features that ease the \pattern{Observer} 
	design pattern implementation are delegates and events in C\#. 
	They are supported in C\# because the \pattern{Observer} pattern 
	is suitable for event driven applications, which are developed in the .NET 
	quiet often. Java and Swing, on the other side, use the \pattern{Command} 
	pattern to invoke some code in response to a GUI 
	event. Implementing each event response as a separate class (command) is not 
	so tedious in Java as it would be in C\#, because Java supports anonymous 
	classes, which are missing from C\#.	
	
	Some modern languages support advanced and innovative 
	features in the field of object oriented programming, which could ease the 
	implementation of design patterns even more. Such features include 
	aspects or meta-programming. Special tools can also enable these in C\# or Java. 
	The implementation of some of the design patterns in ApectJ, aspect oriented 
	extension for Java, is presented in \cite{hannemann2002design}. 
	\cite{osterlie2002ruby} 
	presents Ruby's advanced features (e.g., meta programming) 
	that simplifies the implementation of design patterns.
	
	\subsection{New design problems}
	The new features of programming languages bring us also new design problems. 
	An example might be the pattern from the .NET that we call 
	\pattern{Flexible Generic Interface}, which leverages .NET feature of 
	an explicit interface implementation to overcome the problem of implementing 
	non-generic interfaces (e.g., \inlinecode{IEnumerable}) and their generic 
	counterparts (e.g., \inlinecode{IEnumerable<T>}) in a one class.	
		
	Imagine that we implement a graph library in .NET. We have the \inlinecode{IGraph} 
	interface aggregating edges and vertices and we want it to be flexible, so 
	we don't restrict the vertices to be objects of any specific type. This way users 
	can create a graph containing integers and strings at the same time. 
	The example of such 
	interface is in the figure~\ref{fig:igraph}.	
	\begin{figure}		
		\begin{lstlisting}[language=C]
interface IGraph
{
	IEnumerable Vertices { get; }
	IEdge { get; set; }
}
		\end{lstlisting}
		\caption{Non-generic \inlinecode{IGraph} interface}
		\label{fig:igraph}
	\end{figure}	
	
	Now users can add whatever they want as a vertex, but some users may want 
	to work with just a one type of vertices. In the case of the non-generic \inlinecode{IGraph} 
	they would have to cast all the objects they get from the \inlinecode{IGraph} interface. 
	An unnecessary casting was one of the reasons for introducing the generics into 
	the .NET runtime. The generic version of the \inlinecode{IGraph} interface 
	might look like in the figure~\ref{fig:igraphgen}.	
	\begin{figure}		
		\begin{lstlisting}[language=C]
interface IGraph<T>
{
	IEnumerable<T> Vertices { get; }
	IEdge<T> { get; set; }
}
		\end{lstlisting}
		\caption{Generic \inlinecode{IGraph} interface}
		\label{fig:igraphgen}
	\end{figure}	
		
	If we had these two interfaces separately, then we would have to implement 
	each graph algorithm in two versions -- one for the generic, and the other 
	for the non-generic version of the \inlinecode{IGraph} interface. 
	This is far from ideal, so what we do is to let 
	the generic interface implement the non-generic one. Because the names 
	of the members are the same, we have to use the \inlinecode{new} keyword 
	as in the figure~\ref{fig:igraphgen2}.	
	\begin{figure}		
		\begin{lstlisting}[language=C]
interface IGraph<T> : IGraph
{
	new IEnumerable<T> Vertices { get; }
	new IEdge<T> { get; set; }
}
		\end{lstlisting}
		\caption{Generic \inlinecode{IGraph} interface implements the non-generic one.}
		\label{fig:igraphgen2}
	\end{figure}		
	
	How shall we now implement the new interface? That is where the explicit 
	interface implementation comes to play. The generic methods are implemented 
	as usual, but the non-generic methods are implemented using this feature. 
	We can see a fragment of the implementation in figure \ref{fig:graphgen3}.
	A consequence of this implementation is that we have to explicitly cast 
	the class to non-generic \inlinecode{IGraph} if we want to work with the 
	non-generic versions of the methods, but normally we don't want to do so, 
	unless we pass our graph as a parameter to an algorithm which works only 
	with the non-generic version of the interface, but in such case case, 
	the cast is done automatically.	
	\begin{figure}		
		\begin{lstlisting}[language=C]
class Graph<T> : IGraph<T> {
	private IList<T> vertices = new List<T>();	
	public IEnumerable<T> Vertices { 
		get { return this.vertices; } 
	}
	IEnumerable IGraph.Vertices { 
		get { return (IEnumerable)this.vertices; }
	}	
	// ...
}
		\end{lstlisting}
		\caption{Fragment of implementation of the generic \inlinecode{IGraph} interface.}
		\label{fig:graphgen3}
	\end{figure}		
		
	\subsection{Future trends}
	The mainstream programming languages are usually not adopting new features 
	because their authors want to ease the implementation of design patterns, 
	but they normally adopt features that help to solve more general problems 
	such as lambda functions. These features might make some design patterns obsolete 
	or almost disappear, for instance, the \pattern{Observer} pattern in .NET, but 
	they also might bring new challenges. The authors of the mainstream programming 
	languages, usually corporations or standardization committees, don't want to 
	add features that will be only useful in some rare situations, 
	because then the language would be overcomplicated.
	Some patterns (e.g., the \pattern{Flyweight} pattern) are too 
	complex, abstract or not so widely used, so that direct support for 
	their implementation in 
	languages such as Java or C\# is not likely in the near future. 	
	
\section{Tools support}
\label{sec:toolssupport}
Some of the complexity of implementing and maintaining design patterns is 
caused by an introduction of new classes and new methods into the design. 
During the development, the connection between the classes and the concrete design 
patterns roles might be lost and the system that used to be well designed, 
perfectly lucid and easily extensible becomes the exact opposite. 
Design patterns might provide an abstraction that helps to develop 
large software systems. For example, when a specific class hierarchy 
does not change often, but the operations over these classes are being constantly 
added or removed, then the \pattern{Visitor} pattern is suitable. Developers 
who already know the \pattern{Visitor} pattern don't need to study how the double 
dispatch in this pattern is implemented. If they want to add a new operation and 
they have the information that these classes can be visited by an instance of the 
\pattern{Visitor}, the task becomes easy. However, if the intent to use 
the \pattern{Visitor} pattern is not clear, some developers might start 
adding new operations directly to the classes that can be visited and 
the system becomes inconsistent. One could conclude that, if the system had 
been designed without the \pattern{Visitor} pattern 
from the first moment, it could paradoxically be better.

The reasons for possible misunderstanding when design patterns are involved in 
the code might be either a complete lack of a documentation, or either an inaccuracy of 
a textual documentation in natural language. One possibility to overcome 
these problems might be a standardized documentation of design patterns 
instances. For the Java platform there is a project called JPatterns 
(\cite{jpatterns:Online}), which provides the annotations to mark patterns 
in Java code. At the moment it only provides a javadoc documentation for 
the annotations and the annotations itself. We are not aware of any similar 
approach for the .NET platform. 

The standardized documentation won't prevent developers from violating 
the principles of implemented design patterns, although it could help 
a lot with this problem. To take even more advantage of the documentation, 
a verification tool that would enforce some aspects of design patterns 
could be implemented. Such tool might, for example, prevent a developer 
from direct communication with an object of specific type, when this 
communication should in fact be done through the \pattern{Mediator} object. 

Moreover, during the process of implementing a pattern, the abstract idea 
behind the pattern is broken down into several classes or methods. With 
a standardized documentation we could reconstruct it back a thus 
provide a more abstract view on the software system.

While tools for formal verification and tools for reconstructing abstract 
design patterns from a set of concrete classes exist, most of them 
do not leverage standardized documentation of design 
patterns that is located directly in 
the code and direct location of documentation in the source code may motivate 
developers to keep it up to date. Moreover, except for few of these tools, 
they didn't get enough attention from the industry and most of them 
target the Java platform, but only few target the .NET platform.

Some of the reasons why the industry is not adopting the design patterns 
verification tools may be too much mathematical formalism involved in their usage. 
For definition of new patterns, knowledge of formal logic is usually required. 

Tools that reconstruct abstract design patterns from a set of concrete classes 
are mostly based on an automatic recognition of design patterns, 
whose advantage is that it does not require additional work from developers 
and can be used for legacy systems, but it's disadvantage is that it cannot 
correctly recognize all the design patterns, since some of them don't differ 
in the solution part, or are too much abstract to berecognized only 
from the source code.

\subsection{Patterns4Net}
In order to evaluate the ideas stated in the previous paragraphs, we 
implemented a prototype project called Patterns4Net, which is a set of 
tools that support the development of an object oriented 
software on the .NET platform. These tools take advantage of a special documentation 
about patterns solution participants (in the following text referred as 
"patterns meta-data"), which is usually expressed using custom .NET attributes 
provided by Patterns4Net (in the following text referred as "Patterns4Net 
attributes"), but this mechanism is extensible and the patterns meta-data may 
be discovered using, for example, naming conventions, or anything else that can be 
inferred from CIL meta-data.
There are predefined patterns in the standard distribution of Patterns4Net, 
but users can add their own patterns. Patterns4Net consists of Pattern Enforcer 
and Architecture Explorer tools.

Pattern Enforcer checks marked pattern implementations in .NET assemblies 
against constraints written in C\# using special API. Users can add constraints 
for their custom patterns or even just idioms or simple conventions 
such as "all methods in domain classes should invoke \inlinecode{Logger.Log} method".

Architecture Explorer leverages the patterns documentation to generate UML-like 
class diagrams that support a notion of zooming in and out which adds or removes 
details from the diagram. Such way a developer can have a general overview of the 
architecture or he can zoom to a specific class and see all related classes. 
The decision whether class should be displayed in the general overview or whether 
it should be displayed only in the highest zoom is based on the patterns 
roles it implements. Some patterns represents rather an infrastructural detail, 
on the other hand, for instance, patterns from \cite{evans2004domain} or from 
\cite{fowler2002patterns} are usually represented by domain specific classes.






